<template>
  <div id="UserLoginPage">
    <h2 style="margin-bottom: 32px">设置题目</h2>

    <a-form
      :model="questionList"
      :style="{ width: '480px', margin: '0 auto' }"
      label-align="left"
      auto-label-width
      @submit="handleSubmit"
    >
      <a-form-item label="应用名称">
        {{ app?.appName }}
      </a-form-item>
      <a-form-item label="题目列表" :content-flex="false" :merge-props="false">
        <a-space size="large">
          <a-button @click="QuestionAdd(questionList.length)"
            >底部添加题目
          </a-button>
          <AiDrawer
            v-if="APP_SCORING_STRATEGY_EUM.AI === app?.scoringStrategy"
            :appId="appId"
            :onSuccess="onAiGenerateSuccess"
            :onSSEStart="onSSEStart"
            :onSSEClose="onSSEClose"
            :onSSESuccess="onAiGenerateSuccessSSE"
          />
        </a-space>

        <div v-for="(question, index) in questionList" :key="index">
          <a-space size="large">
            <h3>题目{{ index + 1 }}</h3>
            <a-button size="small" @click="QuestionAdd(index + 1)"
              >添加题目
            </a-button>
            <a-button
              size="small"
              @click="QuestionDelete(index)"
              status="danger"
              >删除题目
            </a-button>
          </a-space>
          <a-form-item :label="`题目 ${index + 1} 标题`">
            <a-input v-model="question.title" placeholder="请输入题目" />
          </a-form-item>
          <!--  题目选项-->
          <a-space size="large">
            <h4>题目{{ index + 1 }}选项列表</h4>
            <a-button
              size="small"
              @click="QuestionAddOption(question, question.options.length)"
              >底部添加选项
            </a-button>
          </a-space>
          <a-form-item
            v-for="(option, optionIndex) in question.options"
            :key="optionIndex"
            :label="`选项 ${optionIndex}`"
            :content-flex="false"
            :merge-props="false"
          >
            <a-form-item label="选项key">
              <a-input v-model="option.key" placeholder="请输入选项key" />
            </a-form-item>
            <a-form-item label="选项value">
              <a-input v-model="option.value" placeholder="请输入选项value" />
            </a-form-item>
            <a-form-item label="选项结果">
              <a-input v-model="option.result" placeholder="请输入选项结果" />
            </a-form-item>
            <a-form-item label="选项得分">
              <a-input-number
                v-model="option.score"
                placeholder="请输入选项得分"
              />
            </a-form-item>
            <a-space size="large">
              <a-button
                size="mini"
                @click="QuestionAddOption(question, optionIndex + 1)"
                >添加选项
              </a-button>
              <a-button
                size="mini"
                @click="QuestionDeleteOption(question, optionIndex)"
                status="danger"
                >删除选项
              </a-button>
            </a-space>
          </a-form-item>
        </div>
      </a-form-item>

      <a-form-item>
        <a-space>
          <a-button type="primary" html-type="submit" style="width: 120px"
            >提交
          </a-button>

          <a-button
            type="primary"
            :href="`/app/detail/${props.appId}`"
            style="width: 120px"
            >返回
          </a-button>
        </a-space>
      </a-form-item>
    </a-form>
  </div>
</template>

<script setup lang="ts">
import { defineProps, reactive, ref, watchEffect, withDefaults } from "vue";
import { useLoginUserStore } from "@/store/userStore";
import meassage from "@arco-design/web-vue/es/message";
import API from "@/api";
import { useRouter } from "vue-router";

import message from "@arco-design/web-vue/es/message";
import {
  addQuestionUsingPost,
  editQuestionUsingPost,
  listQuestionVoByPageUsingPost,
} from "@/api/questionController";
import AiDrawer from "@/views/add/compoents/AiDrawer.vue";
import { getAppVoByIdUsingGet } from "@/api/appController";
import { APP_SCORING_STRATEGY_EUM } from "@/constant/app";

const loginUserStore = useLoginUserStore();
const router = useRouter();
const form = ref({
  appDesc: "",
  appIcon: "",
  appName: "",
  appType: 0,
  scoringStrategy: 0,
} as API.AppAddRequest);

interface Props {
  appId: string;
}

const props = withDefaults(defineProps<Props>(), {
  appId: () => {
    return "";
  },
});
//题目结构
const questionList = ref([] as API.QuestionContenDto[]);

//添加题目
const QuestionAdd = (index: number) => {
  questionList.value.splice(index, 0, {
    title: "",
    options: [],
  });
};
//删除题目
const QuestionDelete = (index: number) => {
  questionList.value.splice(index, 1);
};
//添加题目选项
const QuestionAddOption = (question: API.QuestionContenDto, index: number) => {
  if (!question.options) {
    question.options = [];
  }
  question.options.splice(index, 0, {
    key: "",
    value: "",
  });
};
//删除题目选项
const QuestionDeleteOption = (
  question: API.QuestionContenDto,
  index: number
) => {
  if (!question.options) {
    question.options = [];
  }
  question.options.splice(index, 1);
};

const oldQuestion = ref<API.QuestionVO>();
const app = ref<API.AppVO>();

const loadData = async () => {
  if (!props.appId) {
    return;
  }
  let res;

  res = await getAppVoByIdUsingGet({
    id: props.appId as any,
  });
  if (res.data.code === 0 && res.data.data) {
    app.value = res.data.data;
  }

  res = await listQuestionVoByPageUsingPost({
    appId: props.appId as any,
    current: 1,
    pageSize: 1,
    sortField: "createTime",
    sortOrder: "descend",
  });
  if (res.data.code === 0 && res.data.data?.records) {
    oldQuestion.value = res.data.data.records[0];
    if (oldQuestion.value) {
      questionList.value = oldQuestion.value.questionContent ?? [];
    }
  } else {
    message.error("获取数据失败，" + res.data.message);
  }
};
/**
 * 获取旧数据
 */
watchEffect(() => {
  loadData();
});

/**
 * 提交
 * @param data
 */
const handleSubmit = async () => {
  if (!props.appId || !questionList.value) {
    return;
  }
  let res: any;
  //如果是修改
  if (oldQuestion.value?.id) {
    res = await editQuestionUsingPost({
      id: oldQuestion.value?.id,
      questionContent: questionList.value,
    });
  } else {
    res = await addQuestionUsingPost({
      appId: props.appId as any,
      questionContent: questionList.value,
    });
  }

  if (res.data.code === 0) {
    await loginUserStore.fetchLoginUser();
    meassage.success("创建成功，即将跳转到应用详情页");
    setTimeout(() => {
      router.push({ path: `/app/detail/${props.appId}` });
    }, 3000);
  } else {
    meassage.error("创建失败," + res.data.message);
  }
};
/**
 * AI生成题目后执行
 * @param result
 */

const onAiGenerateSuccess = (result: API.QuestionContenDto[]) => {
  questionList.value = [...questionList.value, ...result];
  message.success(`AI 生成题目成功，已新增 ${result.length} 道题目`);
};

/**
 * AI生成题目后执行(SSE)
 * @param result
 */

const onAiGenerateSuccessSSE = (result: API.QuestionContenDto) => {
  questionList.value = [...questionList.value, result];
};
/**
 * sse开始生成
 * @param event
 */
const onSSEStart = (event: any) => {
  message.success("AI 生成题目中，请稍后");
};
/**
 * sse关闭
 * @param event
 */
const onSSEClose = (event: any) => {
  message.success("AI 生成题目结束");
};
</script>
